package cn.pigeon.health.service;

import cn.pigeon.health.pojo.Permission;
import cn.pigeon.health.pojo.Role;
import cn.pigeon.health.pojo.User;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * spring security 框架相关的查找用户信息的类,框架自动调用
 */
@Component
public class SpringSecurityUserService implements UserDetailsService {
    @Reference
    private UserService userService;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //按用户名称调用远程服务到数据库中查找出用户信息
        User findUser = userService.findByUserName(username);
        if(findUser==null){
            return null;
        }

        //给用户授权
        List<GrantedAuthority> lst = new ArrayList<>();
        for (Role role : findUser.getRoles()) {
            //授予角色
            lst.add(new SimpleGrantedAuthority(role.getKeyword()));
            for (Permission permission : role.getPermissions()) {
                //授予权限
                lst.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }

        return new org.springframework.security.core.userdetails.User(username,findUser.getPassword(),lst);
    }
}
